package com.foreveross.bsl.common.utils.balance.zookeeper2;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/** zookeeper操作工具类
 * 
 * @author hyw
 *
 */
public class ZKUtil {

	@Deprecated
	public static ZooKeeper buildSimpleZK(String serverList, int sessionTimeout) throws IOException {
		return new ZooKeeper(serverList, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// do nothing.
			}
		});
	}
	
	public static void buildPath(ZooKeeper zk, String aliveServicePath, CreateMode createMode) throws KeeperException, InterruptedException {
		// "/a/b/c/"
		String[] paths = aliveServicePath.split("/");
		String assembledPath = "";
		
		for (int i = 0; i < paths.length; i++) {
			if ("".equals(paths[i])) {
				continue;
			}
			assembledPath = assembledPath + "/" + paths[i];
			if (zk.exists(assembledPath, false) == null && (i != paths.length - 1)) {
				zk.create(assembledPath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			} else if(zk.exists(assembledPath, false) == null && (i == paths.length - 1)) { // 最后一个节点 选择节点有效方式
				zk.create(assembledPath, null, Ids.OPEN_ACL_UNSAFE, 
						(createMode == null ? CreateMode.PERSISTENT : createMode));
			}
		}
	}

    public static List<String> getChildren(ZooKeeper zk, String path) throws KeeperException, InterruptedException {
        List<String> children = Collections.emptyList();
        children = zk.getChildren(path,false);
        return children;
    }

	public static String getData(ZooKeeper zk, String path) throws Exception {
		Stat stat;
		stat = zk.exists(path, false);
		if(stat == null)
			return null;
		return new String(zk.getData(path, false, stat), "UTF-8");
	}

	public static String getParentPath(String childPath) {
		if (StringUtils.isBlank(childPath) || !childPath.contains("/")) {
			throw new IllegalArgumentException("childPath不是合法的子路径，childPath=" + childPath);
		}

		String parentPath = "";
		String[] nodeArr = childPath.split("/");
		for (int i = 0; i < nodeArr.length - 1; i++) {
			if (i == 0) {
				parentPath = nodeArr[i];
			} else {
				parentPath = parentPath + "/" + nodeArr[i];
			}
		}
		return parentPath;
	}
}
